<template>
    <main class="work">
        <div class="draw" ref="draw" @mousemove="onDrawMousemove">
            <div class="scale">
                <div class="scale_z"></div>
                <div class="scale_x">
                    <canvas></canvas>
                </div>
                <div class="scale_y">
                    <canvas></canvas>
                </div>
            </div>
            <div ref="drop" :class="['canvas', canvas.showDrag &&'dragstart']" @wheel="handleWheel" @mousedown="onCanvasMousedown" @mousemove="onCanvasMousemove"  @mouseup="onMouseup" @contextmenu.stop="onContextmenu">
                <svg ref="msvg" class="svg" id="svg" xmlns="http://www.w3.org/2000/svg" :width="canvas.docwidth" :height="canvas.docheight" :viewBox="`${canvas.offsetx} ${canvas.offsety} ${canvas.width} ${canvas.height}`" :style="{ background: canvas.background,backsetup }">
                    <template v-for="(group, i) in data" :key="i">
                        {{ group.selected }}
                        <g @mousedown="onSvgMousedown($event, 2, 1)" @mouseup="onMouseup" :class="group.selected ? 'selected' : 'node'">{{ group.box }}
                            <rect :x="group.box[0][0]" :y="group.box[0][1]" rx="0" ry="0" :width="group.box[1][0]-group.box[0][0]" :height="group.box[1][1]-group.box[0][1]" class="group"></rect>
                        </g>
                        <g v-for="(item, j) in group.sensor" :key="j"  @mousedown="onSvgMousedown($event, i, j)" @mouseup="onMouseup" :class="item.selected ? 'selected' : 'node'">
                            <rect :x="item.box[0][0]" :y="item.box[0][1]" :rx="0" :ry="0" :width="Math.abs(item.box[1][0]-item.box[0][0])" :height="Math.abs(item.box[1][1]-item.box[0][1])" class="sensor"></rect>
                        </g>
                    </template>
                    <g v-html="svg"></g>
                </svg>
            </div>
            <div class="subline">
                <div class="subline_x" :style="[{ top: canvas.lineY + 'px' }]"></div>
                <div class="subline_y" :style="[{ left: canvas.lineX + 'px' }]"></div>
            </div>
        </div>
    </main>
</template>
<script>
    import { ref, reactive, watch, computed, onMounted, onUnmounted } from 'vue'
    import { uuid, isEmptyObj, getMousePos, getQuadrant, operate, scale } from "../hook";
    import { NS, strokeAnimations } from "../config";
    import { useEventListener } from '@vueuse/core'
    export default {
        name: 'Work',
        props: {
            canvas: {
              type: Object,
              default: {}
            },
            data: {
              type: Object,
              default: null
            },
            svg: {
              type: String,
              default: ""
            },
            control: {
              type: String,
              default: ""
            }
        },
        data(){
            return {
                isbutton:false,
                isDraw:false,
                mousePos:{x:0, y:0},
                mcanvas: {
                    offsetx: 0,
                    offsety: 0,
                    width: 0,
                    height: 0,
                },
                state:{
                    x: 0,// 基于画布初始坐标x
                    y: 0,// 基于画布初始坐标y
                    x2: 0,// 基于组件移动后的offsetX坐标
                    y2: 0,// 基于组件移动后的offsetY坐标
                    status: false,// 绘制状态
                    alt: false,// 是否按下Alt键
                    ctrl: false,// 是否按下Ctrl键
                    shift: false,// 是否按下Shift键,
                }
            }
        },
        computed:{
            backsetup: function(){
                switch (this.canvas.backsetup) {
                    case 'center':
                        return {
                            'background-repeat': 'no-repeat',
                            'background-position': 'center',
                        }
                    case 'cover':
                        return {
                            'background-size': '100% 100%'
                        }
                    case 'contain':
                        return {
                            'background-size': 'contain',
                            'background-repeat': 'no-repeat',
                            'background-position': 'center',
                        }
                    default:
                        return {
                            'background-size': 'auto'
                        }
                        break;
                }
            }
        },
        methods:{
            /**
             * 鼠标中键在Canvas画布上按下时
             * @param{object} e MouseEvent对象
             */
            handleWheel(e){
                let prevzoom=this.canvas.zoom
                if(e.deltaY<0){
                    this.canvas.zoom=Math.round((this.canvas.zoom-0.1)*10)/10
                }else{
                    this.canvas.zoom=Math.round((this.canvas.zoom+0.1)*10)/10
                }

                let mwidth=this.canvas.width
                let mheight=this.canvas.height
                this.canvas.width=this.canvas.width+this.canvas.width*(this.canvas.zoom-prevzoom)
                this.canvas.height=this.canvas.height+this.canvas.height*(this.canvas.zoom-prevzoom)

                const { width, height } = this.$refs["drop"].getBoundingClientRect()
                const [ postonx, postony ] = getMousePos(this.$refs["drop"], e);
                this.canvas.offsetx =this.canvas.offsetx+postonx/width*(mwidth-this.canvas.width)
                this.canvas.offsety =this.canvas.offsety+postony/height*(mheight-this.canvas.height)
                e.preventDefault();
            },
            reset(){
                this.canvas.width=this.canvas.width+this.canvas.width/this.canvas.zoom
                this.canvas.height=this.canvas.width+this.canvas.height/this.canvas.zoom
                return false;
            },
            /**
             * 鼠标左键在Canvas画布上按下时
             * @param{object} e MouseEvent对象
             */
             onCanvasMousedown (e){
                if(e.button==1){
                    this.isbutton=true;
                }else if(e.button==0){
                    this.isDraw=true;
                }
                [this.state.x, this.state.y]= getMousePos(this.$refs["drop"], e)
                e.preventDefault();
                e.stopPropagation();
                // 如果是在组件上拖拽绘制组件时
                //setInitCoordinate(e);
            },
            onCanvasMousemove (e){
                if(this.isbutton){

                    [this.state.x2, this.state.y2]= getMousePos(this.$refs["drop"], e)
                    let offsetX = this.state.x2 - this.state.x;
                    let offsetY = this.state.y2 - this.state.y;

                    this.canvas.offsetx= this.canvas.offsetx-offsetX*(this.canvas.width/(this.$refs["drop"].offsetWidth))
                    this.canvas.offsety= this.canvas.offsety-offsetY*(this.canvas.height/(this.$refs["drop"].offsetHeight))

                    this.state.x = this.state.x2;
                    this.state.y = this.state.y2;
                }
                //console.log("画布中鼠标移动")
            },
            /**
             * 鼠标左键在画布/组件上抬起
             */
             onMouseup (e){
                if(e.button==1){
                    this.isbutton=false
                }else if(e.button==0){
                    if(this.isDraw){
                        if (this.control=="sensor"){
                            let box=this.getBoxRect(e)
                            this.data.forEach(function(item,index,arr){
                                if(item.box[0]<box[0]&&item.box[1]<box[1]&&item.box[2]>box[2]&&item.box[3]>box[3]){
                                    item["data"].push({
                                        "id": "46",
                                        "name": "",
                                        "sn": "新增加",
                                        "unit": "",
                                        "num": 2,
                                        "price": "",
                                        "total": "",
                                        "produce": "",
                                        "remark": "",
                                        "box": box
                                    })
                                }
                            })
                        }
                    }
                    this.isDraw=false
                }
                if (this.state.status && 'polyline' === prop.nowTool.type) return false;
                return false;
            },

            getBoxRect (e){
                let postion=getMousePos(this.$refs["drop"], e);
                let fff=this.$refs["drop"].getBoundingClientRect()
                let zoom=[this.canvas.width/fff.width,this.canvas.height/fff.height]
                let box=[0, 0, 0, 0]

                if (this.state.x*zoom[0]+this.canvas.offsetx > postion[0]*zoom[0]+this.canvas.offsetx){
                    box[2] = this.state.x * zoom[0]+this.canvas.offsetx
                    box[0] = postion[0]*zoom[0] + this.canvas.offsetx
                }else{
                    box[2] = postion[0] * zoom[0] + this.canvas.offsetx
                    box[0] = this.state.x * zoom[0] + this.canvas.offsetx
                }

                if (this.state.y*zoom[1]+this.canvas.offsety > postion[1]*zoom[1]+this.canvas.offsety){
                    box[3] = this.state.y * zoom[1] + this.canvas.offsety
                    box[1] = postion[1] * zoom[1] + this.canvas.offsety
                }else{
                    box[3] = postion[1] * zoom[1] + this.canvas.offsety
                    box[1] = this.state.y * zoom[1] + this.canvas.offsety
                }
                return box
            },
            /**
             * 显示基于世界坐标系中鼠标坐标的X和Y
             * @param{Object} e MouseEvent对象
             */
            onDrawMousemove (e){
                if (!this.canvas.showLine) return;
                [this.canvas.lineX, this.canvas.lineY] = getMousePos(this.$refs.draw, e)
            },
            onSvgMousedown (e, i, j){
                e.preventDefault();
                e.stopPropagation();
                console.log("svg 鼠标按下")
                this.data[i]["data"][j]["selected"]=!this.data[i]["data"][j]["selected"]
            },
            /**
             * 鼠标左键在画布/组件上抬起
             */
            onKeyup(e) {
                e.preventDefault();
                this.state.alt = false;
                this.state.ctrl = false;
                this.state.shift = false;
                return false;
            },
            onKeydown(e) {
                e.preventDefault();
                return false;
            },
            onContextmenu(e){
                e.preventDefault();
                return false;
            }
        },
        mounted(){
            const oScale = new scale({
                draw: `.draw`,
                canvas: `.canvas`,
                scale_x: `.scale_x`,
                scale_y: `.scale_y`
            });

            // 重置画布标尺刻度
            watch(() => [this.canvas.width, this.canvas.height], (n1, n2) => {
                setTimeout(() => {
                    const { top, left } = this.$refs["drop"].getBoundingClientRect();
                    [this.canvas.dropX, this.canvas.dropY] = [left, top];
                    oScale.reset();
                }, 300);
            }, { immediate: true });
            // 居中辅助线
            this.canvas.lineX = this.$refs.draw.offsetWidth / 2
            this.canvas.lineY = this.$refs.draw.offsetHeight / 2

            useEventListener(document, 'keydown', this.onKeydown)
            useEventListener(document, 'keyup',  this.onKeyup, false)
        },
        unmounted(){
            window.onresize = null;
        },
        watch:{
            svg(val){
                console.log(svg)
            },
            control(val){
                if (val=="reset"){
                    console.log("大小重置")
                    this.reset()
                }
            }
        },
    }
</script>
<style lang="scss" scoped nae>
.work {
    box-sizing: border-box;
    grid-area : work;
    display   : flex;
    overflow  : hidden;

    .draw {
        box-sizing: border-box;
        position  : relative;
        flex      : 1;
        overflow  : auto;
        cursor    : crosshair;

        .scale {
            position      : relative;
            z-index       : 1;
            pointer-events: none;

            &>div {
                position: sticky;
                &>canvas {
                    background: rgb(80, 80, 80);
                }
            }

            .scale_z {
                position: fixed;
                z-index : 2;

                &::after {
                    content   : "";
                    display   : block;
                    width     : 18px;
                    height    : 18px;
                    background: rgb(80, 80, 80);
                    box-shadow: 2px 6px 12px 4px rgba(30, 30, 30, .6);
                }
            }

            .scale_x {
                top       : 0;
                height    : 18px;
                box-shadow: 0px 2px 6px 0px rgba(50, 50, 50, .6);
            }

            .scale_y {
                left      : 0;
                width     : 18px;
                box-shadow: 2px 0px 6px 0px rgba(30, 30, 30, .6);

                &>canvas {
                    position: relative;
                    top     : -18px;
                }
            }
        }

        .canvas {
            box-sizing   : border-box;
            position     : absolute;
            margin       : 0;
            padding      : 0;
            width: 100%;
            height: 99%;
            // border    : 5px dashed transparent;

            .svg {
                box-sizing            : border-box;
                margin                : 0;
                padding               : 0;
                transition            : all .3s cubic-bezier(0.16, 0.66, 0.28, 0.96);
                background-image   : url();
                outline               : 1px solid #EEE;
                .rotate {
                    cursor: url(@/assets/img/rotate.png) 12 12, auto;
                }
                g.selected {
                    outline: 120px solid #F900FF;
                }
                .sensor {
                    stroke: #ff0800; 
                    stroke-width: 200; 
                    stroke-opacity: 1.000; 
                    fill: #cccccc;
                    fill-opacity: 0.5;
                }
                .group {
                    stroke: #ff0000; 
                    stroke-width: 500; 
                    stroke-opacity: 1.000; 
                    fill: none; 
                    fill-opacity: 1.000;
                }
            }
        }

        .dragstart {
            background-color: white;
            border          : 5px dashed #166FFF;
            box-shadow      : 0 0 10px 0 #166FFF;
        }

        .subline {
            position      : sticky;
            top           : 0;
            right         : 0;
            bottom        : 0;
            left          : 0;
            width         : 100%;
            height        : 100%;
            user-select   : none;
            pointer-events: none;

            &>div {
                position        : absolute;
                top             : 0;
                right           : 0;
                bottom          : 0;
                left            : 0;
                background-color: blueviolet;
            }

            .subline_x {
                top             : 0;
                height          : 1px;
                background-image: linear-gradient(to right, blueviolet, deepskyblue);
            }

            .subline_y {
                left            : 0;
                width           : 1px;
                background-image: linear-gradient(deeppink, deepskyblue);
            }
        }
    }
}
</style>